package cqie.frame.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cqie.frame.entity.Dept;
import cqie.frame.entity.Emp;
import cqie.frame.entity.SysUser;
import cqie.frame.entity.po.SelectListItem;
import cqie.frame.entity.qo.EmpQo;
import cqie.frame.entity.vo.EmpVo;
import cqie.frame.response.CodeMsg;
import cqie.frame.response.ResultJson;
import cqie.frame.service.IDeptService;
import cqie.frame.service.IEmpService;
import cqie.frame.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Emp)表控制层
 *
 * @author makejava
 * @since 2021-09-27 08:47:34
 */
@Api
@RestController
@RequestMapping("/emp")
public class EmpController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private IEmpService iempService;
    @Resource
    private IDeptService iDeptService;
    @Resource
    private ISysUserService iSysUserService;


    //新增员工
    @ApiOperation(value = "新增员工", notes = "新增员工，同时更新用户员工表。", response = Emp.class)
    @PostMapping(value = "/addEmp")
    public ResultJson addEmp(@RequestBody Emp po) {
        try {
            //构造mo
            Emp emp = new Emp();
            //复制po的属性到emp,第三个参数可选，为忽略某些属性
            BeanUtils.copyProperties(po, emp);
            //插入用户表后回显插入用户的主键id
            iempService.save(emp);
            po.setId(emp.getId());
            //返回员工
            return ResultJson.success(po);
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //删除选中员工，多选
    @ApiOperation(value = "删除选中员工", notes = "删除选中员工，同时更新员工表。")
    @PostMapping(value = "/deleteCheckEmp")
    public ResultJson deleteCheckEmp(@RequestBody Long[] empIdList) {
        try {
            for (int i = 0; i < empIdList.length; i++) {
                iempService.removeById(empIdList[i]);
            }
            return ResultJson.success("删除成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //删除员工
    @ApiOperation(value = "删除单个员工", notes = "删除单个员工，同时更新员工表。")
    @GetMapping(value = "/deleteEmp")
    public ResultJson deleteEmp(long id) {
        try {
            //删除员工表
            iempService.removeById(id);
            //返回前端
            return ResultJson.success("删除成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


    //修改员工
    @ApiOperation(value = "修改员工", notes = "修改员工，同时更新员工表。")
    @PostMapping(value = "/updateEmp")
    public ResultJson updateEmp(@RequestBody Emp po) {
        try {
            //获取修改前的值
            Emp emp = new Emp();
            //复制po的属性到sysUser,第三个参数可选，为忽略某些属性
            BeanUtils.copyProperties(po, emp);
            //修改员工
            iempService.updateById(emp);
            return ResultJson.success("修改成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


    //根据员工id获取详情
    @ApiOperation(value = "查看详情", response = EmpVo.class)
    @GetMapping(value = "/selectEmpById")
    public ResultJson selectEmpById(Long id) {
        try {
            //1.获取mo
            Emp mo = iempService.getById(id);
            //2.映射成vo
            EmpVo vo = new EmpVo();
            BeanUtils.copyProperties(mo, vo);
            //映射准备
            //映射--性别
            vo.setSexName(mo.getSex() == 0 ? "男" : "女");
            //映射--登录账号
            if (mo.getUserId() != null) {
                SysUser findUser = iSysUserService.getById(mo.getUserId());
                if (findUser != null) {
                    vo.setUserAccount(findUser.getAccount());
                }
            }
            //映射--所在部门
            if (mo.getDeptId() != null) {
                Dept findDept = iDeptService.getById(mo.getDeptId());
                if (findDept != null) {
                    vo.setDeptName(findDept.getName());
                }
            }
            //3.返回
            return ResultJson.success(vo);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


    //查询员工
    @ApiOperation(value = "分页列表", response = EmpVo.class)
    @PostMapping(value = "/listPaged")
    public ResultJson listPaged(@RequestBody EmpQo qo) {
        try {
            Page<Emp> page = new Page<>(qo.getPageIndex(), qo.getPageSize());


            //查询条件,是否输入查询条件，如员工代码，员工账号，员工性别，员工部门等
            //是否查询员工名称
            QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
            if (!StringUtils.isEmpty(qo.getName())) {
                //不为空，启用查询
                //查询模糊查询
                queryWrapper.like("name", qo.getName());
            }
            //是否查询性别
            if (qo.getSex() != null) {
                //不为空，启用查询
                queryWrapper.eq("sex", qo.getSex());
            }
            //是否查询代码
            if (!StringUtils.isEmpty(qo.getCode())) {
                //不为空，启用查询
                //查询模糊查询
                queryWrapper.like("code", qo.getCode());
            }
            //是否查询部门
            if (qo.getDeptId() != null) {
                //不为空，启用查询
                //查询模糊查询
                queryWrapper.like("deptId", qo.getDeptId());
            }
            //2.执行查询
            IPage<Emp> datas = iempService.page(page, queryWrapper);
            //3.生成返回值
            //映射准备--用户
            List<Long> userIdList = datas.getRecords()
                    .stream()
                    .filter(x -> x.getUserId() != null)
                    .map(Emp::getUserId)
                    .distinct()
                    .collect(Collectors.toList());
            List<SysUser> allUser = new ArrayList<>();
            if (userIdList.size() > 0) {
                QueryWrapper<SysUser> qwUser = new QueryWrapper<>();
                qwUser.in("id", userIdList);
                allUser = iSysUserService.list(qwUser);
            }
            //映射准备--所在部门
            List<Long> deptIdList = datas.getRecords()
                    .stream()
                    .filter(x -> x.getDeptId() != null)
                    .map(Emp::getDeptId)
                    .distinct()
                    .collect(Collectors.toList());
            List<Dept> allDept = new ArrayList<>();
            if (deptIdList.size() > 0) {
                QueryWrapper<Dept> qwDept = new QueryWrapper<>();
                qwDept.in("id", deptIdList);
                allDept = iDeptService.list(qwDept);
            }
            //映射
            List<EmpVo> list = new ArrayList<>();
            IPage<EmpVo> ret = new Page<>();
            BeanUtils.copyProperties(datas, ret);
            for (Emp mo : datas.getRecords()) {
                EmpVo vo = new EmpVo();
                BeanUtils.copyProperties(mo, vo);
                //映射--性别
                vo.setSexName(mo.getSex() == 0 ? "男" : "女");
                //映射--登录账号
                if (mo.getUserId() != null) {
                    SysUser findUser = allUser.stream().filter(x -> x.getId().equals(mo.getUserId())).findFirst().orElse(null);
                    if (findUser != null) {
                        vo.setUserAccount(findUser.getAccount());
                    }
                }
                //映射--所在部门
                if (mo.getDeptId() != null) {
                    Dept findDept = allDept.stream().filter(x -> x.getId().equals(mo.getDeptId())).findFirst().orElse(null);
                    if (findDept != null) {
                        vo.setDeptName(findDept.getName());
                    }
                }
                list.add(vo);
            }
            ret.setRecords(list);
            return ResultJson.success(ret);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "获取用户备选项", response = SelectListItem.class)
    @GetMapping(value = "/listUsers")
    public ResultJson listUsers(Long empId) {
        try {
            List<SelectListItem> ret = new ArrayList<>();
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            String notInSql = "select userId from emp where userId is not null";
            qw.notInSql("id", notInSql);
            qw.eq("status", 0);
            List<SysUser> allUser = iSysUserService.list(qw);
            for (SysUser mo : allUser) {
                ret.add(SelectListItem.SelectListItem(mo.getId(), mo.getAccount()));
            }
            if (empId != null) {
                Emp emp = iempService.getById(empId);
                if (emp.getUserId() != null) {
                    SysUser sysUser = iSysUserService.getById(emp.getUserId());
                    ret.add(SelectListItem.SelectListItem(sysUser.getId(), sysUser.getAccount()));
                }
            }
            return ResultJson.success(ret);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }


}